﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CoderJoe.WoW.GearManager.Views;
using CoderJoe.WoW.Services;
using System.Threading;

namespace CoderJoe.WoW.GearManager
{
	public class CharacterController
		: Controller
	{
		public CharacterModel Model { get; set; }

		public CharacterController(Workspace workspace)
			: base(workspace)
		{
			Model = new CharacterModel();
		}

		public CharacterView GetCharacterView()
		{
			CharacterView view = new CharacterView(this);
			view.Disposed += new EventHandler(View_Disposed);
			Model.SetInvokeOwner(view);
			return view;
		}

		void View_Disposed(object sender, EventArgs e)
		{
			Model.SetInvokeOwner(null);
		}

		internal void RefreshModel(string realm, string name)
		{
			if (!String.IsNullOrEmpty(realm) && !String.IsNullOrEmpty(name))
			{
				CharacterService service = Workspace.Resolve<CharacterService>();
				Character character = service.GetCharacterFromArmory(realm, name);
				Model.LoadModel(character);

				foreach (CharacterItemModel itemModel in Model.Items)
				{
					ThreadPool.QueueUserWorkItem(new WaitCallback(LoadImage), itemModel);
				}
			}
		}

		private void LoadImage(object state)
		{
			CharacterItemModel itemModel = (CharacterItemModel)state;
			if (itemModel.Icon == String.Empty)
			{
				itemModel.Image = Properties.Resources.empty;
			}
			else
			{
				ItemService service = Workspace.Resolve<ItemService>();
				itemModel.Image = service.GetItemImage(itemModel.Icon);
			}
		}
	}
}
